package com.wispx.gateway.core.filter.loadblance.strategy;

import com.wispx.gateway.config.pojo.ServiceInstance;
import com.wispx.gateway.core.context.GatewayContext;

import java.util.List;

import static com.wispx.gateway.common.constant.LoadBalanceConstant.GRAY_LOAD_BALANCE_STRATEGY;

/**
 * 灰度负载均衡
 */
public class GrayLoadBalacneStrategy implements LoadBalanceStrategy {
    @Override
    public ServiceInstance selectInstance(GatewayContext context, List<ServiceInstance> instances) {
        double totalGrayRatio = instances.stream()
                .mapToDouble(ServiceInstance::getGrayRatio)
                .sum();
        int randomGrayRatio = Math.abs(context.getRequest().getHost().hashCode()) % (int) (totalGrayRatio * 100);
        for (ServiceInstance instance : instances) {
            randomGrayRatio -= instance.getGrayRatio();
            if (randomGrayRatio <= 0D) {
                return instance;
            }
        }
        return null;
    }

    @Override
    public String mark() {
        return GRAY_LOAD_BALANCE_STRATEGY;
    }
}
